//
//  ShlRecordManager.m
//  CommonAppSHL
//
//  Created by mac on 2021/6/7.
//

#import "ShlRecordManager.h"

@interface ShlRecordManager ()<AVAudioPlayerDelegate,AVAudioRecorderDelegate>
// 麦克风权限
@property(nonatomic,assign)BOOL is_per;
@end

@implementation ShlRecordManager
// 单例
+ (instancetype)manager{
    static ShlRecordManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ShlRecordManager alloc] init];
    });
    return manager;
}
// 初始化录音格式类型
- (void)initFilePathWithType:(NSInteger)record_type{
    self.record_type = record_type;
    switch (record_type) {
        case 0:
        {
            [self setCafWriterConfig];
        }
            break;
        case 1:
        {
            [self setAmrWriterConfig];
        }
            break;
        case 2:
        {
            [self setMp3WriterConfig];
        }
            break;
            
        default:
            break;
    }
}

- (void)setCafWriterConfig{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    CafRecordWriter *writer = [[CafRecordWriter alloc]init];
    writer.filePath = [path stringByAppendingPathComponent:@"record.caf"];
    self.cafWriter = writer;
    
    MLAudioMeterObserver *meterObserver = [[MLAudioMeterObserver alloc]init];
    meterObserver.actionBlock = ^(NSArray *levelMeterStates,MLAudioMeterObserver *meterObserver){
        SQ_LOG(@"volume:%f",[MLAudioMeterObserver volumeForLevelMeterStates:levelMeterStates]);
    };
    meterObserver.errorBlock = ^(NSError *error,MLAudioMeterObserver *meterObserver){
        SQ_LOG(@"录音发生错误");
    };
    self.meterObserver = meterObserver;

    MLAudioRecorder *recorder = [[MLAudioRecorder alloc]init];
    __weak __typeof(self)weakSelf = self;
    recorder.receiveStoppedBlock = ^{
//        [weakSelf.recordButton setTitle:@"Record" forState:UIControlStateNormal];
        weakSelf.meterObserver.audioQueue = nil;
    };
    recorder.receiveErrorBlock = ^(NSError *error){
//        [weakSelf.recordButton setTitle:@"Record" forState:UIControlStateNormal];
        weakSelf.meterObserver.audioQueue = nil;

        SQ_LOG(@"录音发生错误");
    };


    //caf
    recorder.fileWriterDelegate = writer;
    //self.filePath = writer.filePath;
    self.recorder = recorder;
}
- (void)setAmrWriterConfig{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    AmrRecordWriter *amrWriter = [[AmrRecordWriter alloc]init];
    amrWriter.filePath = [path stringByAppendingPathComponent:@"record.amr"];
    amrWriter.maxSecondCount = 60;
    amrWriter.maxFileSize = 1024*256;
    self.amrWriter = amrWriter;
    
    
    MLAudioMeterObserver *meterObserver = [[MLAudioMeterObserver alloc]init];
    meterObserver.actionBlock = ^(NSArray *levelMeterStates,MLAudioMeterObserver *meterObserver){
        SQ_LOG(@"volume:%f",[MLAudioMeterObserver volumeForLevelMeterStates:levelMeterStates]);
    };
    meterObserver.errorBlock = ^(NSError *error,MLAudioMeterObserver *meterObserver){
        SQ_LOG(@"录音发生错误");
    };
    self.meterObserver = meterObserver;

    MLAudioRecorder *recorder = [[MLAudioRecorder alloc]init];
    __weak __typeof(self)weakSelf = self;
    recorder.receiveStoppedBlock = ^{
//        [weakSelf.recordButton setTitle:@"Record" forState:UIControlStateNormal];
        weakSelf.meterObserver.audioQueue = nil;
    };
    recorder.receiveErrorBlock = ^(NSError *error){
//        [weakSelf.recordButton setTitle:@"Record" forState:UIControlStateNormal];
        weakSelf.meterObserver.audioQueue = nil;
        SQ_LOG(@"录音发生错误");
    };

    //amr
    recorder.bufferDurationSeconds = 0.25;
    recorder.fileWriterDelegate = self.amrWriter;

    self.recorder = recorder;
    
}
- (void)setMp3WriterConfig{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    Mp3RecordWriter *mp3Writer = [[Mp3RecordWriter alloc]init];
    mp3Writer.filePath = [path stringByAppendingPathComponent:@"record.mp3"];
    mp3Writer.maxSecondCount = 60;
    mp3Writer.maxFileSize = 1024*256;
//    mp3Writer.maxSecondCount = 300;
//    mp3Writer.maxFileSize = 1024*256 * 100;
    self.mp3Writer = mp3Writer;
    
    MLAudioMeterObserver *meterObserver = [[MLAudioMeterObserver alloc]init];
    meterObserver.actionBlock = ^(NSArray *levelMeterStates,MLAudioMeterObserver *meterObserver){
        SQ_LOG(@"volume:%f",[MLAudioMeterObserver volumeForLevelMeterStates:levelMeterStates]);
    };
    meterObserver.errorBlock = ^(NSError *error,MLAudioMeterObserver *meterObserver){
        SQ_LOG(@"录音发生错误");
    };
    self.meterObserver = meterObserver;

    MLAudioRecorder *recorder = [[MLAudioRecorder alloc]init];
    __weak __typeof(self)weakSelf = self;
    recorder.receiveStoppedBlock = ^{
//        [weakSelf.recordButton setTitle:@"Record" forState:UIControlStateNormal];
        weakSelf.meterObserver.audioQueue = nil;
    };
    recorder.receiveErrorBlock = ^(NSError *error){
//        [weakSelf.recordButton setTitle:@"Record" forState:UIControlStateNormal];
        weakSelf.meterObserver.audioQueue = nil;
        SQ_LOG(@"录音发生错误");
    };

    //mp3
    recorder.fileWriterDelegate = mp3Writer;
    //self.filePath = mp3Writer.filePath;

    self.recorder = recorder;
}
// 请求麦克风权限
- (BOOL)RequestPermission{
    // 请求麦克风权限
    __weak typeof(self) weakself = self;
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        weakself.is_per = granted;
    }];
    return self.is_per;
}
// 开始录制
- (void)startRecord{
    // 删除本地之前存在的录音文件
    [self deleteAllFile];
    // 请求麦克风权限
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        if (granted) {// 存在权限
            SQ_LOG(@"开始录制");
            [self.recorder startRecording];
            self.meterObserver.audioQueue = self.recorder->_audioQueue;
        }else{
            // 不存在权限
        }
    }];
}
// 结束录制
- (void)stopRecord{
    [self.recorder stopRecording];
    SQ_LOG(@"%@-------%@",_amrWriter.filePath,_mp3Writer.filePath);
}
// mp3结束录制，返回base64的字符串
- (NSString *)stopMp3Record{
    [self.recorder stopRecording];
    return [self mp3ToBASE64:_mp3Writer.filePath];
}
// 播放录制语音
- (void)playRecord{
    //如果正在录音，则停止录音
    if (self.recorder.isRecording) {
        [self.recorder stopRecording];
    }
    
    //设置类别,AVAudioSessionCategoryPlayAndRecord表示该应用同时支持播放和录音
    // AVAudioSessionCategoryPlayback 表示只支持录音，不能同时播放
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
    //启动音频会话管理,此时会阻断后台音乐的播放.
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    // 如果当前在播放，停止
    if (_audioPlayer.isPlaying) {
        [_audioPlayer stop];
    }
   
    if (self.record_type == 0) {
        long long fileLength = [self fileSizeAtPath:self.cafWriter.filePath];
        NSLog(@"%lld",fileLength);
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:self.cafWriter.filePath] error:nil];
        _audioPlayer.delegate = self;
        [_audioPlayer play];
    }else if (self.record_type == 1){
        long long fileLength = [self fileSizeAtPath:self.amrWriter.filePath];
        NSLog(@"%lld",fileLength);
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:self.amrWriter.filePath] error:nil];
        _audioPlayer.delegate = self;
        [_audioPlayer play];
    }else if (self.record_type == 2){
        long long fileLength = [self fileSizeAtPath:_mp3Writer.filePath];
        NSLog(@"%lld",fileLength);
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:self.mp3Writer.filePath] error:nil];
        _audioPlayer.delegate = self;
        [_audioPlayer play];
    }
    
}

//计算文件大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
// 将mp3 转成base64字符串
- (NSString *)mp3ToBASE64:(NSString *)filePath{
    NSData *mp3Data = [NSData dataWithContentsOfFile:filePath];
    NSString *_encodedImageStr = [mp3Data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    //[mp3Data base64Encoding];
//    NSLog(@"===Encoded image:\n%@", _encodedImageStr);
    return _encodedImageStr;
 }
// 移出指定path的文件
- (void)deleteFileWithPath:(NSString *)filePath{
    // 移出指定path的文件
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:filePath error:nil];
    
}
// 移出所有path的文件
- (void)deleteAllFile{
    // 删除本地之前存在的录音文件
    if ([NSTemporaryDirectory() stringByAppendingString:@"record.mp3"]){
        [self deleteFileWithPath:[NSTemporaryDirectory() stringByAppendingString:@"record.mp3"]];
    }
    if ([NSTemporaryDirectory() stringByAppendingString:@"record.caf"]){
        [self deleteFileWithPath:[NSTemporaryDirectory() stringByAppendingString:@"record.caf"]];
    }
    if ([NSTemporaryDirectory() stringByAppendingString:@"record.amr"]){
        [self deleteFileWithPath:[NSTemporaryDirectory() stringByAppendingString:@"record.amr"]];
    }
    
}
/**
 *  代理方法的实现
 */


- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    SQ_LOG(@"录音播放完成");
    
}
/* if an error occurs while decoding it will be reported to the delegate. */
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error{
    if (error) {
        NSLog(@"录音播放出现错误：%@",error);
    }
}
@end
